<?php

namespace Apps\AppApi\Method\BeautyParlor;

use AliYun\OpenSearch;
use AMap\LBSCloud;
use Apps\Common\Libs\PicUrl;
use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Models\BeautyParlorTag;
use Apps\Common\Models\BeautyParlorTagInfo;
use Apps\Common\Models\BeautyParlorAttr;
use PhalconPlus\Api\Common\ResultStatus;
use Apps\Common\Models\SysOpenCity;
use Apps\Common\Models\OmBanner;
use Apps\Common\Models\BeautyParlor;

/**
 * 附近美容院
 * @package Apps\AppApi\Method\BeautyParlor
 */
class Lbstest extends BaseMethod
{
    /**
     * @var \Apps\Common\Models\BeautyParlor array
     */
    private $parlors = [];

    public function run()
    {
        //先验证城市是否开通 modify by tanjinyun 2016/01/11
        $city_code = $this->getDataItem('city_code');

        if ($city_code == null || $city_code == '') {
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, "城市编码为空");
            exit;
        }
        $is_open = SysOpenCity::findFirst(
            [
                'columns' => "city_id",
                'conditions' => "city_code = $city_code AND city_state = 1",
            ]);

        if (!$is_open->city_id > 0) {
            return $this->errorLog(ResultStatus::CITY_NOT_OPEN, "城市未开通");
            exit;
        }
        $longitude = $this->getDataItem('longitude', 0);
        $latitude = $this->getDataItem('latitude', 0);
        $page = intval($this->getDataItem('page', 1));
        $medal = intval($this->getDataItem('medal', 0));
        $keyword = trim($this->getDataItem('keyword', null));
        $tag_title = trim($this->getDataItem('tag_title', null));
        $limit = $this->getConfig()->limit;

        // 阿里云搜索
        $op = new OpenSearch('cmeelier3', 'dUBfr1wNHjgMnJsd', '1U6ZSbOKhGBffxsopuMIKN6xCpSzUe', 'aliyun', 'http://opensearch-cn-beijing.aliyuncs.com');
        $res = $op->search_two('state', '1', 'distance(lon,lat,"' . $longitude . '","' . $latitude . '")<30&&kvpairs=+longtitude2:' . $longitude . ',latitude2:' . $latitude . '&&sort=+distance(lon,lat,"' . $longitude . '","' . $latitude . '")', $limit, $page * $limit - $limit, $keyword, $medal, $tag_title);

        $arrs = [];
        foreach ($res['result']['items'] as $k => $v) {
            $arrs[$k]['id'] = $v['fields']['bp_id'];
            $arrs[$k]['name'] = $v['fields']['bp_name'];
            $arrs[$k]['address'] = $v['fields']['bp_address'];
            $arrs[$k]['cover'] = PicUrl::BeautyParlorCover($v['fields']['bp_cover'], $this->getDi());
            $arrs[$k]['tel'] = $v['fields']['bp_tel'];
            $arrs[$k]['tags'] = $this->formatTagsV2($v['fields']['bp_id']);
            $arrs[$k]['medal_verify'] = \Apps\Common\Libs\BeautyParlor::getMedalVerify($v['fields']['bp_medal']);
            $arrs[$k]['open_time'] = $v['fields']['open_time'];
            $arrs[$k]['close_time'] = $v['fields']['close_time'];
            $arrs[$k]['low_price'] = $v['fields']['low_price'];
            $arrs[$k]['open_year'] = $v['fields']['open_year'];
            $arrs[$k]['shop_area'] = $v['fields']['shop_area'];
            $arrs[$k]['service_num'] = $v['fields']['service_num'];
            $arrs[$k]['facilities'] = $v['fields']['facilities'] == null ? null : (json_decode($v['fields']['facilities']) ?: null);
            $arrs[$k]['distance'] = $this->formatDistance($v['variableValue']['extinfo'][0]);
        }


        /**
         * 第一页获取banner
         */
        if ($page == 1) {


            $banner = OmBanner::query()
                ->columns(['banner_data'])
                ->where('state = 1 AND banner_name =3 AND city_id in(0, :city_id:)')
                ->bind(['city_id' => $is_open->city_id])
                ->execute()->toArray();

            foreach ($banner as $k => $v) {

                $data = json_decode($v['banner_data']);

                $temp[$k]['url'] = PicUrl::DefaultPics($data->url, $this->getDi());
                $temp[$k]['link_type'] = $data->link_type;
                $temp[$k]['link_data'] = !empty(json_decode($data->link_data)) ? json_decode($data->link_data) : null;
            }
        }


        $list['banner'] = $temp;
//        $list['parlors'] = empty($this->parlors) ? null : $this->parlors;
        $list['parlors'] = $arrs;

        $this->setResult($list);
    }

    /**
     * v2版本 不验证 是否存在标签数据 都当标签已存在
     * @date: 2016年1月11日
     * @author: 545
     */
    private function formatTagsV2($bp_id)
    {
        $tag = $this->getBeautyParlorTags($bp_id);
        return $tag;
    }

    /**
     * 格式化标签
     * @date: 2016年1月11日
     * @author: 545
     */
    private function formatTags($tags, $bp_id)
    {
        $ds = [];
        if ($tags) {
            $ds = explode(',', $tags);
            foreach ($ds as $r) {
                $wherearr[] = "Apps\Common\Models\BeautyParlorTagInfo.tag_title = '$r' and b.bp_id = $bp_id";
            }
            $where = implode(" or ", $wherearr);
            $list = BeautyParlorTagInfo::query()
                ->columns(['Apps\Common\Models\BeautyParlorTagInfo.tag_title', 'b.sort'])
                ->leftJoin('Apps\Common\Models\BeautyParlorTag', 'Apps\Common\Models\BeautyParlorTagInfo.tag_id=b.tag_id', 'b')
                ->where($where)
                ->orderBy('b.sort asc')
                ->execute()->toArray();
        }
        unset($ds);
        foreach ($list as $r) {
            $ds[] = $r['tag_title'];
        }
        return $ds;
    }

    private function formatDistance($distance)
    {
        if ($distance > 1) {
            $distance = round($distance, 2) . 'KM';
        } else {
            $distance = round($distance * 1000, 2) . 'M';
        }
        return $distance;
    }
}
/*
 * id	店铺ID
name	店铺名称
cover	封面
address	地址
tags	店铺标签数组，最多设置3个
distance	距离
medal_refund	退款保障，1-拥有此属性，0-没有此属性
medal_verify	深度验店，1-拥有此属性，0-没有此属性
 */